<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="评测标题" prop="evalutionName">
        <el-input
          v-model="queryParams.evalutionName"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['evalution.topic.edit']" >新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="topicList">
      <el-table-column label="编号" align="center" prop="instanceId" />
      <el-table-column label="评测标题" align="center" prop="evalutionName" />
      <el-table-column label="状态" align="center" prop="statusName" />
      <el-table-column label="截止时间" align="center" prop="planEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注说明" align="center" prop="mark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status>0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
          >查看</el-button>
          <el-button v-if="scope.row.status==0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['evalution.topic.edit']"
          >修改</el-button>
          <el-button v-if="scope.row.status==0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['evalution.topic.edit']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改实验室评测对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="11">
          <el-form-item label="评测标题" prop="evalutionName">
            <el-input v-model="form.evalutionName" placeholder="请输入标题" />
          </el-form-item>
          </el-col>
          <el-col :span="11">
          <el-form-item label="截止时间" prop="planEndTime">
            <el-date-picker clearable size="small" style="width: 300px"
              v-model="form.planEndTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择截止时间">
            </el-date-picker>
          </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注说明" prop="mark">
          <el-input type="textarea" rows="3" v-model="form.mark" placeholder="请输入备注说明"  style="width: 650px;"/>
        </el-form-item>
        <div class="form_table">
          <el-table :data="form.topicTaskList" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }">
            <el-table-column label="实验中心" min-width="260">
              <template slot-scope="scope">
               <treeselect v-model="scope.row.orgId" :options="deptOptions" :default-expand-level="2"
               :show-count="true" placeholder="请输入实验中心" append-to-body z-index="9999" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="自查工号">
              <template slot-scope="scope">
                <el-input v-model="scope.row.userName" placeholder="自查工号" @keyup.enter.native="changeUserName(scope.$index)"
                @blur="changeUserName(scope.$index)" ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="自查姓名">
              <template slot-scope="scope">
                <el-input v-model="scope.row.nickName" placeholder="自查姓名" disabled></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" min-width="30">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="listingDelete(scope.$index)"
                  style="margin-top: 0px">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button class="table_button" @click="tableBtn">新增自查实验中心</el-button>
        </div>
        <el-form-item label="测评方案">
         <UploadCom ref="upload" @submitData="submitData" :description="'请上传方案附件'" :userFileList="fileList"
           class="form_long" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="primary" @click="submitFlow" v-if="this.form.instanceId>0">提交</el-button>
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
    <TopicDetails ref="detail"></TopicDetails>
  </div>
</template>

<script>
import { listTopic, getTopic, delTopic, addTopic, updateTopic, submitTopic } from "@/api/evalution/topic";
import UploadCom from "@/views/labdata/commons/upload.vue";
import ChooseUser from "@/views/labdata/employee/user_choose_com.vue";
import { searchEmployee, getEmployeeInfo } from "@/api/labdata/employee";
import { treeselect,getTreeLabel } from "@/api/labdata/orgnization";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import TopicDetails from "@/views/evalution/topic/details"
export default {
  name: "LabTopic",
  components: { UploadCom,ChooseUser,Treeselect, TopicDetails},
  data() {
    return {
      //附件集合
      fileList: [],
      deptOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实验室评测表格数据
      topicList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        evalutionName: null,
        planEndTime: null,
        mark: null,
        finishedTime: null
      },
      // 表单参数
      form: {
        topicTaskList:[],
      },
      // 表单校验
      rules: {
        evalutionName: [
          { required: true, message: "评测标题不能为空", trigger: "blur" }
        ],
        planEndTime: [
          { required: true, message: "截止时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询实验室评测列表 */
    getList() {
      this.loading = true;
      listTopic(this.queryParams).then(response => {
        this.topicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleDetail(row){
      this.$refs["detail"].handleUpdate(row);
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    changeUserName(index) {
      let userName = this.form.topicTaskList[index].userName;
      console.log('userName='+userName);
      if (userName==null) {
        //this.form.topicTaskList[index].userName = null;
        this.form.topicTaskList[index].nickName = null;
        return;
      }
      //console.log(JSON.stringify(event));
      //return;
      searchEmployee(userName).then(response => {
        let searchResult = response.data;
        if (searchResult ) {
          this.form.topicTaskList[index].nickName = searchResult.nickName;
        } else {
          this.form.topicTaskList[index].userName = null;
          this.form.topicTaskList[index].nickName = null;
        }
        //强制刷新
        this.$forceUpdate();
      });
    },
    tableBtn() {
      let obj = {};
      obj.orgId = null;
      obj.orgName = null;
      obj.userName = null;
      obj.nickName = null;
      this.form.topicTaskList.push(obj);
    },
    //删除实验中心
    listingDelete(index) {
      this.form.topicTaskList.splice(index, 1);

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        instanceId: null,
        evalutionName: null,
        planEndTime: null,
        mark: null,
        createTime: null,
        createBy: null,
        finishedTime: null,
        topicTaskList:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.instanceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实验室评测";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //this.reset();
      const instanceId = row.instanceId || this.ids
      getTopic(instanceId).then(response => {
        this.form = response.data;
        if (this.form) {
         this.fileList = this.form.images;
        }
        this.open = true;
        this.title = "修改实验室评测";
      });
    },
    submitFlow(){
      this.form.status = 1;
      this.submitForm();
    },
    /** 提交按钮 */
    submitData(allFiles) {
      this.form.images = allFiles;
      for(var i=0;i<this.form.topicTaskList.length;i++){
            let id = this.form.topicTaskList[i].orgId;
            this.form.topicTaskList[i].orgName = getTreeLabel(this.deptOptions,id);
      }
      if (this.form.instanceId != null) {
        updateTopic(this.form).then(response => {
          this.msgSuccess("修改成功");
          this.form = response.data;
          if(this.form.status>0){
            this.open = false;
            this.getList();
          }
        });
      } else {
        addTopic(this.form).then(response => {
          this.form = response.data;
          this.msgSuccess("新增成功");
          //this.open = false;
          this.getList();
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
           this.$refs["upload"].doSubmit();
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const instanceIds = row.instanceId || this.ids;
      this.$confirm('是否确认删除实验室评测编号为"' + instanceIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTopic(instanceIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
  }
};
</script>
<style scoped lang="scss">
  .table_button {
    width: 100%;
    text-align: center;
    line-height: 20px;
    border-bottom: 1px solid #f6f5f5;
    color: #43bef8;
    cursor: pointer;
    border: 0;
  }
</style>
